package com.example.beautymakeup.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.example.beautymakeup.config.DouyinConfig;
import com.example.beautymakeup.dto.DouyinAuthDTO;
import com.example.beautymakeup.service.DouyinAuthService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class DouyinAuthServiceImpl implements DouyinAuthService {
    
    @Autowired
    private DouyinConfig douyinConfig;

    @Override
    public String getAuthorizationUrl(DouyinAuthDTO authDTO) {
        Map<String, String> params = new HashMap<>();
        params.put("client_id", authDTO.getClientId());
        params.put("redirect_uri", authDTO.getRedirectUri());
        params.put("response_type", "code");
        params.put("scope", "order.query");
        return douyinConfig.getAuthUrl() + "?" + buildQueryString(params);
    }

    @Override
    public String exchangeAccessToken(DouyinAuthDTO authDTO) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("code", authDTO.getCode());
        params.put("client_id", authDTO.getClientId());
        params.put("client_secret", authDTO.getClientSecret());
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", authDTO.getRedirectUri());

        String response = HttpUtil.get(douyinConfig.getTokenUrl(), params);
        JSONObject json = JSONObject.parseObject(response);
        if (json.getInteger("code") == 0) {
            return json.getJSONObject("data").getString("access_token");
        }
        throw new RuntimeException("获取access_token失败: " + json.getString("message"));
    }

    private String buildQueryString(Map<String, String> params) {
        List<String> paramList = new ArrayList<>();
        params.entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(entry -> paramList.add(entry.getKey() + "=" + entry.getValue()));
        return String.join("&", paramList);
    }
}